﻿using MySql.Data.MySqlClient;
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace MySQLBackupApp
{
    public partial class MainForm : Form
    {
        private DateTime nextBackupTime;
        private TimeSpan interval;
        private bool isDailyBackup = true;

        public MainForm()
        {
            InitializeComponent();
            LoadSettings();
            btnStopBackup.Enabled = false;
        }

        private void LoadSettings()
        {
            try
            {
                txtServer.Text = ConfigurationManager.AppSettings["Server"] ?? "";
                txtPort.Text = ConfigurationManager.AppSettings["Port"] ?? "3306";
                txtDatabase.Text = ConfigurationManager.AppSettings["Database"] ?? "";
                txtUsername.Text = ConfigurationManager.AppSettings["Username"] ?? "";
                txtPassword.Text = ConfigurationManager.AppSettings["Password"] ?? "";
                txtBackupPath.Text = ConfigurationManager.AppSettings["BackupPath"] ?? "";

                string backupType = ConfigurationManager.AppSettings["BackupType"] ?? "Daily";
                isDailyBackup = backupType == "Daily";
                rbDaily.Checked = isDailyBackup;
                rbInterval.Checked = !isDailyBackup;

                if (isDailyBackup)
                {
                    string dailyTime = ConfigurationManager.AppSettings["DailyTime"] ?? DateTime.Now.ToString("HH:mm:ss");
                    dtpBackupTime.Value = DateTime.Parse(dailyTime);
                }
                else
                {
                    int hours = int.TryParse(ConfigurationManager.AppSettings["IntervalHours"], out hours) ? hours : 0;
                    int minutes = int.TryParse(ConfigurationManager.AppSettings["IntervalMinutes"], out minutes) ? minutes : 30;
                    nudHours.Value = hours;
                    nudMinutes.Value = minutes;
                    interval = new TimeSpan(hours, minutes, 0);
                }
                chkRunAtStartup.Checked = bool.Parse(ConfigurationManager.AppSettings["RunAtStartup"]);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载设置时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void SaveSettings()
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.AppSettings.Settings["Server"].Value = txtServer.Text;
                config.AppSettings.Settings["Port"].Value = txtPort.Text;
                config.AppSettings.Settings["Database"].Value = txtDatabase.Text;
                config.AppSettings.Settings["Username"].Value = txtUsername.Text;
                config.AppSettings.Settings["Password"].Value = txtPassword.Text;
                config.AppSettings.Settings["BackupPath"].Value = txtBackupPath.Text;
                config.AppSettings.Settings["BackupType"].Value = isDailyBackup ? "Daily" : "Interval";

                if (isDailyBackup)
                {
                    config.AppSettings.Settings["DailyTime"].Value = dtpBackupTime.Value.ToString("HH:mm:ss");
                }
                else
                {
                    config.AppSettings.Settings["IntervalHours"].Value = nudHours.Value.ToString();
                    config.AppSettings.Settings["IntervalMinutes"].Value = nudMinutes.Value.ToString();
                }
                config.AppSettings.Settings["RunAtStartup"].Value = chkRunAtStartup.Checked.ToString();
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");

                MessageBox.Show("设置已保存", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存设置时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            try
            {
                string connectionString = GetConnectionString();
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    connection.Open();
                    MessageBox.Show("连接成功!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"连接失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string GetConnectionString()
        {
            return $"Server={txtServer.Text};Port={txtPort.Text};Database={txtDatabase.Text};Uid={txtUsername.Text};Pwd={txtPassword.Text};";
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
            {
                folderDialog.Description = "选择备份文件保存路径";
                if (folderDialog.ShowDialog() == DialogResult.OK)
                {
                    txtBackupPath.Text = folderDialog.SelectedPath;
                }
            }
        }

        private void rbDaily_CheckedChanged(object sender, EventArgs e)
        {
            isDailyBackup = rbDaily.Checked;
            dtpBackupTime.Enabled = isDailyBackup;
            nudHours.Enabled = !isDailyBackup;
            nudMinutes.Enabled = !isDailyBackup;
        }

        private void rbInterval_CheckedChanged(object sender, EventArgs e)
        {
            isDailyBackup = !rbInterval.Checked;
            dtpBackupTime.Enabled = isDailyBackup;
            nudHours.Enabled = !isDailyBackup;
            nudMinutes.Enabled = !isDailyBackup;
        }

        private void btnSaveSettings_Click(object sender, EventArgs e)
        {
            SaveSettings();
            CalculateNextBackupTime();
        }

        private void CalculateNextBackupTime()
        {
            if (isDailyBackup)
            {
                DateTime now = DateTime.Now;
                DateTime scheduledTime = new DateTime(now.Year, now.Month, now.Day,
                    dtpBackupTime.Value.Hour, dtpBackupTime.Value.Minute, dtpBackupTime.Value.Second);

                if (scheduledTime < now)
                {
                    scheduledTime = scheduledTime.AddDays(1);
                }

                nextBackupTime = scheduledTime;
            }
            else
            {
                interval = new TimeSpan((int)nudHours.Value, (int)nudMinutes.Value, 0);
                nextBackupTime = DateTime.Now.Add(interval);
            }

            lblStatus.Text = $"状态: 下一次备份时间 {nextBackupTime:yyyy-MM-dd HH:mm:ss}";
        }

        private void btnStartBackup_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtServer.Text) || string.IsNullOrEmpty(txtDatabase.Text) ||
                string.IsNullOrEmpty(txtUsername.Text) || string.IsNullOrEmpty(txtPassword.Text) ||
                string.IsNullOrEmpty(txtBackupPath.Text))
            {
                MessageBox.Show("请填写所有必要信息并保存设置", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            CalculateNextBackupTime();
            timerBackup.Start();
            btnStartBackup.Enabled = false;
            btnStopBackup.Enabled = true;
            lblStatus.Text = $"状态: 备份服务已启动，下一次备份时间 {nextBackupTime:yyyy-MM-dd HH:mm:ss}";
        }

        private void btnStopBackup_Click(object sender, EventArgs e)
        {
            timerBackup.Stop();
            btnStartBackup.Enabled = true;
            btnStopBackup.Enabled = false;
            lblStatus.Text = "状态: 备份服务已停止";
        }

        private void timerBackup_Tick(object sender, EventArgs e)
        {
            if (DateTime.Now >= nextBackupTime)
            {
                PerformBackup();
                CalculateNextBackupTime();
            }
        }

        private void PerformBackup()
        {
            try
            {
                lblStatus.Text = "状态: 正在备份...";
                Application.DoEvents();

                string backupPath = txtBackupPath.Text;
                if (!Directory.Exists(backupPath))
                {
                    Directory.CreateDirectory(backupPath);
                }

                string fileName = $"backup_{DateTime.Now:yyyyMMdd_HHmmss}.sql";
                string fullPath = Path.Combine(backupPath, fileName);

                using (MySqlConnection conn = new MySqlConnection(GetConnectionString()))
                {
                    using (MySqlCommand cmd = new MySqlCommand())
                    {
                        using (MySqlBackup mb = new MySqlBackup(cmd))
                        {
                            cmd.Connection = conn;
                            conn.Open();
                            mb.ExportToFile(fullPath);
                            conn.Close();
                        }
                    }
                }

                lblStatus.Text = $"状态: 备份成功 - {fileName}";
            }
            catch (Exception ex)
            {
                lblStatus.Text = $"状态: 备份失败 - {ex.Message}";
                MessageBox.Show($"备份过程中出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void chkRunAtStartup_CheckedChanged(object sender, EventArgs e)
        {
            ApplyStartupSetting();
        }

        private void ApplyStartupSetting()
        {
            try
            {
                string keyName = "MySQLBackupApp";
                string exePath = Application.ExecutablePath;

                Microsoft.Win32.RegistryKey key =
                    Microsoft.Win32.Registry.CurrentUser.OpenSubKey(
                        "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

                if (chkRunAtStartup.Checked)
                {
                    key.SetValue(keyName, exePath);
                }
                else
                {
                    key.DeleteValue(keyName, false);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("设置开机启动项时出错: " + ex.Message, "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnHide_Click(object sender, EventArgs e)
        {
            this.Hide();               // 隐藏窗体  
            this.ShowInTaskbar = false; // 从任务栏移除  
            notifyIcon1.Visible = true; // 显示托盘图标  
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Show();            // 显示窗体  
                this.WindowState = FormWindowState.Normal; // 恢复默认状态  
                this.ShowInTaskbar = true;  // 在任务栏显示  
                notifyIcon1.Visible = false; // 隐藏托盘图标  
            }
        }
    }
}